const fs = require("fs");
const path = require("path");
const vueCompiler = require("vue-template-compiler");

let idCounter = 0;
const usedIds = new Set();

function generateUniqueId(componentName, filePath) {
  const fileName = path.basename(filePath, ".vue");
  const baseId = `${componentName.replace("el-", "")}-${fileName}-${++idCounter}`;
  let finalId = baseId;
  let suffix = 1;

  while (usedIds.has(finalId)) {
    finalId = `${baseId}-${suffix++}`;
  }

  usedIds.add(finalId);
  return finalId;
}

function detectIndentation(template) {
  const lines = template.split("\n");
  for (const line of lines) {
    if (line.trim() && line.startsWith(" ")) {
      const match = line.match(/^(\s+)/);
      if (match) {
        return match[1];
      }
    }
  }
  return "  ";
}

const modifyVueFile = (filePath) => {
  try {
    const content = fs.readFileSync(filePath, "utf-8");
    const parsed = vueCompiler.parseComponent(content);
    const template = parsed.template ? parsed.template.content : "";

    if (!template) {
      console.log(`⚠️  没有template的文件: ${filePath}`);
      return false;
    }

    let hasChanges = false;

    // 匹配所有支持的组件
    const componentRegex =
      /<\s*(el-input|el-button|el-select|el-radio-group|el-switch|el-checkbox|el-radio|el-date-picker|el-time-picker|el-cascader|el-slider|el-rate|el-color-picker|el-transfer|el-form|el-table|el-tree|el-pagination|el-dialog|el-tooltip|el-popover|el-card|el-tabs|el-steps|el-breadcrumb|el-dropdown|el-menu|el-upload)(\s+[^>]*?)?(\s*\/?>)/gi;

    const modifiedTemplate = template.replace(componentRegex, (match, componentName, attrs = "", closing) => {
      const idMatch = /\sid\s*=\s*(['"]?)([^'">\s]+)\1/i.exec(attrs);

      if (!idMatch) {
        const id = generateUniqueId(componentName, filePath);
        hasChanges = true;

        // 如果有属性，在属性前添加id；如果没有属性，直接添加id
        const newAttrs = attrs ? ` id="${id}"${attrs}` : ` id="${id}"`;
        return `<${componentName}${newAttrs}${closing}`;
      }

      return match;
    });

    if (!hasChanges) {
      console.log(`✅ 没有需要更新的组件: ${filePath}`);
      return true;
    }

    // 检测原始缩进并保持一致
    const originalIndentation = detectIndentation(template);
    const indentedModifiedTemplate = modifiedTemplate
      .split("\n")
      .map((line) => (line.trim() ? originalIndentation + line : line))
      .join("\n");

    const templateRegex = /(<template[^>]*>)([\s\S]*?)(<\/template>)/i;
    const templateMatch = content.match(templateRegex);

    if (!templateMatch) {
      console.log(`❌ 无法找到template标签: ${filePath}`);
      return false;
    }

    const newContent = content.replace(templateRegex, `$1${indentedModifiedTemplate}$3`);

    fs.writeFileSync(filePath, newContent, "utf-8");
    console.log(`✅ 成功更新文件: ${filePath}`);
    return true;
  } catch (error) {
    console.error(`❌ 处理文件时出错 ${filePath}:`, error.message);
    return false;
  }
};

const modifyFilesInDirectory = (directoryPath) => {
  let stats = { processed: 0, modified: 0, errors: 0 };

  try {
    const files = fs.readdirSync(directoryPath);

    files.forEach((file) => {
      const filePath = path.join(directoryPath, file);

      try {
        const stat = fs.statSync(filePath);

        if (stat.isDirectory()) {
          const subStats = modifyFilesInDirectory(filePath);
          stats.processed += subStats.processed;
          stats.modified += subStats.modified;
          stats.errors += subStats.errors;
        } else if (file.endsWith(".vue")) {
          console.log(`🔍 处理文件: ${filePath}`);
          stats.processed++;

          if (modifyVueFile(filePath)) {
            stats.modified++;
          } else {
            stats.errors++;
          }
        }
      } catch (error) {
        console.error(`❌ 访问文件/目录时出错 ${filePath}:`, error.message);
        stats.errors++;
      }
    });
  } catch (error) {
    console.error(`❌ 读取目录时出错 ${directoryPath}:`, error.message);
    stats.errors++;
  }

  return stats;
};

const processTarget = (targetPath) => {
  try {
    const stat = fs.statSync(targetPath);

    if (stat.isFile()) {
      if (targetPath.endsWith(".vue")) {
        console.log(`🔍 处理单个文件: ${targetPath}`);
        const success = modifyVueFile(targetPath);
        console.log(`\n📊 处理结果:`);
        console.log(`   文件数量: 1`);
        console.log(`   ${success ? "成功" : "失败"}: 1`);
      } else {
        console.log(`❌ 错误: ${targetPath} 不是Vue文件`);
      }
    } else if (stat.isDirectory()) {
      console.log(`🔍 处理目录: ${targetPath}`);
      const stats = modifyFilesInDirectory(targetPath);

      console.log(`\n📊 处理结果:`);
      console.log(`   处理文件数: ${stats.processed}`);
      console.log(`   成功修改数: ${stats.modified}`);
      console.log(`   错误数量: ${stats.errors}`);
    } else {
      console.log(`❌ 错误: ${targetPath} 不是有效的文件或目录`);
    }
  } catch (error) {
    console.error(`❌ 访问路径时出错 ${targetPath}:`, error.message);
  }
};

const main = () => {
  const targetPath = process.argv[2];

  if (!targetPath) {
    console.log(`
📝 Vue组件ID自动添加工具

用法: node vue-compiler-id.js <文件或目录路径>

    `);
    return;
  }

  const resolvedPath = path.resolve(targetPath);

  if (!fs.existsSync(resolvedPath)) {
    console.log(`❌ 错误: 路径不存在 ${resolvedPath}`);
    return;
  }

  console.log(`🚀 开始处理: ${resolvedPath}\n`);
  processTarget(resolvedPath);
  console.log(`\n✨ 处理完成!`);
};

main();
